#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/02/12
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from json import dumps
from flask import jsonify, session
from flasky.common import AxiosMessage
from flasky.model import Gate, Camera, LED168, Cashier


class AxiosManager(AxiosMessage):
    # 接口消息管理器
    def __init__(self) -> None:
        super().__init__()
        self.__dev = {'gate':'閘機', 'camera':'相機', 'led': 'LED屏幕', 'cashier': '收費處'}
        self.__condition = {"gate": "GateFilter", "camera": "CameraFilter", "led": "LEDFilter", 'cashier': 'CashierFilter'}

    def __get_filter(self, view):
        """
        获取筛选条件
        """
        key = self.__condition.get(view)
        if key:
            filters = session.get(key)
            if filters:
                return jsonify(**filters)
        return key

    def __reset_filter(self, view):
        """
        重置筛选条件
        """
        key = self.__condition.get(view)
        if key:
            filters = session.get(key)
            if filters:
                del session[key]
        return key

    def __set_filter(self, view, filters):
        """
        筛选器
        """
        key = self.__condition.get(view)
        if key:
            session[key] = filters
        return self.success("數據準備中，請稍候")

    def __select_device(self, view, dev_id):
        """
        选中设备
        """
        ret = None
        if view == 'gate':
            ret = Gate.query.filter_by(GateID=dev_id).first()
        elif view == 'camera':
            ret = Camera.query.filter_by(CameraID=dev_id).first()
        elif view == 'led':
            ret = LED168.query.filter_by(LEDID=dev_id).first()
        elif view == 'cashier':
            ret = Cashier.query.filter_by(CashierName=dev_id).first()
        if ret:
            return jsonify(**ret.to_dict())

    def __delete_device(self, view, dev):
        """
        删除设备
        """
        ret = None
        if view == 'gate':
            ret = Gate.delete_device(**dev)
        elif view == 'camera':
            ret = Camera.delete_device(**dev)
        elif view == 'led':
            ret = LED168.delete_device(**dev)
        elif view == 'cashier':
            ret = Cashier.delete_device(**dev)
        if ret:
            return self.success(f"刪除{self.__dev.get(view)}設備成功!")
        return self.warning(f"刪除{self.__dev.get(view)}設備失敗!")

    def __modify_device(self, view, dev):
        """
        修改设备
        """
        ret = None
        if view == 'gate':
            ret = Gate.modify_device(**dev)
        elif view == 'camera':
            ret = Camera.modify_device(**dev)
        elif view == 'led':
            ret = LED168.modify_device(**dev)
        elif view == 'cashier':
            ret = Cashier.modify_device(**dev)
        if ret:
            return self.success(f"更新{self.__dev.get(view)}設備成功!")
        return self.warning(f"更新{self.__dev.get(view)}設備失敗!")

    def __add_device(self, view, dev):
        """
        新增设备
        """
        ret = None
        if view == 'gate':
            ret = Gate.add_device(**dev)
        elif view == 'camera':
            ret = Camera.add_device(**dev)
        elif view == 'led':
            ret = LED168.add_device(**dev)
        elif view == 'cashier':
            ret = Cashier.add_device(**dev)
        if ret:
            return self.success(f"添加{self.__dev.get(view)}設備成功!")
        return self.warning(f"添加{self.__dev.get(view)}設備失敗!")

    def messages(self, **kwargs):
        """
        消息处理
        """
        view = kwargs.get('View')
        for k, v in kwargs.items():
            if k == "Add":
                return self.__add_device(view, v)
            elif k == "Update":
                return self.__modify_device(view, v)
            elif k == "Delete":
                return self.__delete_device(view, v)
            elif k == "GetDevice":
                return self.__select_device(view, v)
            elif k == "SetFilter":
                return self.__set_filter(view, v)
            elif k == "GetFilter":
                return self.__get_filter(view)
            elif k == "ResetFilter":
                return self.__reset_filter(view)
            
    def __columns_name(self, view):
        """
        数据表标题
        """
        if view == "gate":
            return Gate.columns_name()
        elif view == "camera":
            return Camera.columns_name()
        elif view == "led":
            return LED168.columns_name()
        elif view == "cashier":
            return Cashier.columns_name()

    def __data_filter(self, filters, view):
        """
        数据过滤
        """
        if filters is not None and len(filters) > 0:
            if view == "gate":
                return Gate.query.filter(*filters).all()
            elif view == "camera":
                return Camera.query.filter(*filters).all()
            elif view == "led":
                return LED168.query.filter(*filters).all()
            elif view == "cashier":
                return Cashier.query.filter(*filters).all()
        else:
            if view == "gate":
                return Gate.query.all()
            elif view == "camera":
                return Camera.query.all()
            elif view == "led":
                return LED168.query.all()
            elif view == "cashier":
                return Cashier.query.all()

    def __identify_filters(self, view):
        """
        分析过滤器
        """
        filters = set()
        if view == "gate":
            # 闸机
            filters = session.get('GateFilter')
            if filters:
                return Gate.generate_filters(**filters)
        elif view == "camera":
            # 识别相机
            filters = session.get('CameraFilter')
            if filters:
                return Camera.generate_filters(**filters)
        elif view == "led":
            # LED筛选
            filters = session.get('LEDFilter')
            if filters:
                return LED168.generate_filters(**filters)
        elif view == "cashier":
            # 收费处筛选
            filters = session.get('CashierFilter')
            if filters:
                return Cashier.generate_filters(**filters)
        return filters

    def page_data_init(self, view):
        """
        设备页面数据
        """
        # 检查筛选器
        filters = self.__identify_filters(view)
        datas = self.__data_filter(filters, view)
        column_name = self.__columns_name(view)
        return {"ColumnName":column_name, "ColumnNameJSON": dumps(column_name,ensure_ascii=False), "Device": datas}
